﻿using Ldt.DataEngine.DataFlowParse.Model;
using LDT.CoreLibrary;
using LdtDataEngin.ModuleDetail.CommonModule.DataDeduce;
using LdtDataEngin.ModuleDetail.CommonModule.PersonMerger;
using LdtJudge.DataEngine.CallInterface.ConfiCenter;
using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.Common.XmlUtility;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.Collection;
using LdtJudge.DataEngine.Model.Dudection;
using LdtJudge.DataEngine.Model.XMLConfigModel.DataStores;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace LdtDataEngin.ModuleDetail.CommonModule
{
    /// <summary>
    /// 数据推导服务
    /// </summary>
    public class DataDeduceDetail
    {
        private DataContext dataContext { get; }

        private string _moudleName;

        public static List<RequestDataModel> DeduceRequestModels = new List<RequestDataModel>();

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dataContextIn">上下文</param>
        /// <param name="moudleName">模块名称</param>
        public DataDeduceDetail(DataContext dataContextIn, string moudleName)
        {
            dataContext = dataContextIn;
            _moudleName = moudleName;
        }
        public void Extrat()
        {
            //模块配置
            ConfigModel moudelConfig = dataContext.DataLayerSys.GetConfigModel(_moudleName);

            ConfigModel dataDeduceConfig = moudelConfig.ConfigDetail?.FirstOrDefault(x => x.Code.ToLower() == "invokeduc");
            if (dataDeduceConfig != null)
            {
                string xml = string.Empty;
                if (dataDeduceConfig.ExecuteType == "xml")
                {
                    xml = dataDeduceConfig.ConfigContent;
                }
                else
                {
                    Dictionary<string, string> dicElement = new Dictionary<string, string>();
                    string url = dataDeduceConfig.FilePath;
                    url = url.Replace("{casetype}", dataContext.DataLayerAns.CaseType);
                    dicElement.Add("fileFullName", url);
                    string elementMessage = WebUtil.DoGet(ConfigRetrieval.GetConfigRetrieval.GetAppSettingString("systemapi") + "/api/WordParse/GetConfigFileContent", dicElement, "utf-8");
                    dynamic elementcofig = JsonConvert.DeserializeObject<dynamic>(elementMessage);
                    if (elementcofig.result.code.ToString() == "1")
                    {
                        xml = elementcofig.body;
                    }
                }
                if (!string.IsNullOrWhiteSpace(xml))
                {
                    datadeduce deduceModel = XmlSerializeHelper.DESerializer<datadeduce>(xml);
                    var deduceItem = deduceModel.datadeduceitem.FirstOrDefault();
                    if (deduceItem != null)
                    {
                        if (!string.IsNullOrWhiteSpace(deduceItem.sourcecode))
                        {
                            List<string> sourceCodes = deduceItem.sourcecode.ToLower().Split(",").ToList();
                            if (sourceCodes.Contains(dataContext.DataLayerAns.SourceCode.ToLower()))
                            {
                                var paramterList = GetDeduceInputModel(deduceItem.type);
                                foreach (var paramter in paramterList)
                                {
                                    Dictionary<string, List<string>> re = new Dictionary<string, List<string>>();

                                    re = GetDeduceResult(paramter, deduceItem.code, deduceItem.project, deduceItem.type);
                                    if (re.Count > 0)
                                    {
                                        int flag = GetFlag(deduceItem.type);

                                        UpdateXml(re, flag, paramter.outParameter.FirstOrDefault(a => a.code == "CaseCauseID").Value);
                                    }
                                }
                                if (deduceItem.type == "ao")
                                {
                                    try
                                    {
                                        dataContext.InteractiveShow.LogShow("执行法律法规数据填充");
                                        QutoLawdeByidDuction qutoLawdeByidDuction = new QutoLawdeByidDuction() { dataContext = dataContext, moudleName = _moudleName };
                                        qutoLawdeByidDuction.LawDuction();
                                    }
                                    catch (Exception ex)
                                    {
                                        dataContext.InteractiveShow.LogShow("执行法律法规数据填充错误" + ex.ToString());
                                    }
                                }
                            }
                        }
                    }

                    if (deduceItem.type == "po")
                    {
                        SituationPlotData situationPlotData = new SituationPlotData() { dataContext = dataContext };
                        situationPlotData.Merge();
                    }
                }
            }
        }

        /// <summary>
        /// 根据类型获取转换标志
        /// </summary>
        /// <param name="type">类型 ae:分析后推导 ao:优选后推导 po:分人员要素分析后推导 pom:分人员要素优选后，合并前推导，aom案件要素优选后推导。</param>
        /// <returns>标志值</returns>
        public static int GetFlag(string type)
        {
            int flag = -1;
            switch (type)
            {
                case "ae":
                    flag = 0;
                    break;
                case "ao":
                case "aom":
                    flag = 1;
                    break;
                case "po":
                    flag = 2;
                    break;
                case "pom":
                    flag = 3;
                    break;
            }
            return flag;
        }

        /// <summary>
        /// 根据type生成推导请求参数
        /// </summary>
        public List<DeduceInputModel> GetDeduceInputModel(string type)
        {
            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon();
            List<DeduceInputModel> deduceInputModelList = new List<DeduceInputModel>();
            List<string> causeIds = dataContext.DataLayerAns.CaseCausesList?.Select(x => x.CC_ID).ToList();
            if (type == "ae" || type == "po")
            {
                if (dataContext.DataLayerAns.ElementAnalsisDataModelResults != null && dataContext.DataLayerAns.ElementAnalsisDataModelResults.Count > 0)
                {
                    foreach (var resultmodel in dataContext.DataLayerAns.ElementAnalsisDataModelResults)
                    {
                        XmlDocument causeXml = xmlUtilCommon.DataModelByXml(resultmodel.Value, "");
                        DeduceInputModel result = SetDeduceInput("MSCaseDeduction", dataContext.DataLayerAns.CaseId, dataContext.DataLayerAns.CaseType, resultmodel.Key,
                                dataContext.DataLayerAns.Shujuneirong.Anjianid, HttpHelp.EnDataBase64(dataContext.DataLayerAns.AnalysisResultsXml.OuterXml), HttpHelp.EnDataBase64(causeXml.OuterXml));
                        deduceInputModelList.Add(result);
                    }
                }
                else
                {
                    if (causeIds != null && causeIds.Any())
                    {
                        foreach (var item in causeIds)
                        {
                            DeduceInputModel result = SetDeduceInput("MSCaseDeduction", dataContext.DataLayerAns.CaseId, dataContext.DataLayerAns.CaseType, item,
                                dataContext.DataLayerAns.Shujuneirong.Anjianid, HttpHelp.EnDataBase64(dataContext.DataLayerOpt.OptimizationXml.OuterXml), "");
                            deduceInputModelList.Add(result);
                        }
                    }
                    else
                    {
                        DeduceInputModel result = SetDeduceInput("MSCaseDeduction", dataContext.DataLayerAns.CaseId, dataContext.DataLayerAns.CaseType, "",
                                dataContext.DataLayerAns.Shujuneirong.Anjianid, HttpHelp.EnDataBase64(dataContext.DataLayerOpt.OptimizationXml.OuterXml), "");
                        deduceInputModelList.Add(result);
                    }
                }
            }
            else if (type == "ao")
            {
                if (dataContext.DataLayerOpt.MergeElementXml != null && dataContext.DataLayerOpt.MergeElementXml.Count > 0)
                {
                    foreach (var resultmodel in dataContext.DataLayerOpt.MergeElementXml)
                    {
                        DeduceInputModel result = SetDeduceInput("MSCaseDeduction", dataContext.DataLayerAns.CaseId, dataContext.DataLayerAns.CaseType, resultmodel.Key,
                               dataContext.DataLayerAns.Shujuneirong.Anjianid, HttpHelp.EnDataBase64(dataContext.DataLayerOpt.OptimizationXml.OuterXml), HttpHelp.EnDataBase64(resultmodel.Value.OuterXml));
                        deduceInputModelList.Add(result);
                    }
                }
                else
                {
                    if (causeIds != null && causeIds.Any())
                    {
                        foreach (var item in causeIds)
                        {
                            DeduceInputModel result = SetDeduceInput("MSCaseDeduction", dataContext.DataLayerAns.CaseId, dataContext.DataLayerAns.CaseType, item,
                                dataContext.DataLayerAns.Shujuneirong.Anjianid, HttpHelp.EnDataBase64(dataContext.DataLayerOpt.OptimizationXml.OuterXml), "");
                            deduceInputModelList.Add(result);
                        }
                    }
                    else
                    {
                        DeduceInputModel result = SetDeduceInput("MSCaseDeduction", dataContext.DataLayerAns.CaseId, dataContext.DataLayerAns.CaseType, "",
                                dataContext.DataLayerAns.Shujuneirong.Anjianid, HttpHelp.EnDataBase64(dataContext.DataLayerOpt.OptimizationXml.OuterXml), "");
                        deduceInputModelList.Add(result);
                    }

                }
            }
            else if (type == "pom")
            {
                if (dataContext.DataLayerOpt.ElementOptimizationResults != null && dataContext.DataLayerOpt.ElementOptimizationResults.Count > 0)
                {
                    foreach (var resultmodel in dataContext.DataLayerOpt.ElementOptimizationResults)
                    {
                        DeduceInputModel result = SetDeduceInput("MSCaseDeduction", dataContext.DataLayerAns.CaseId, dataContext.DataLayerAns.CaseType, resultmodel.Key,
                                dataContext.DataLayerAns.Shujuneirong.Anjianid, HttpHelp.EnDataBase64(dataContext.DataLayerOpt.OptimizationXml.OuterXml), HttpHelp.EnDataBase64(xmlUtilCommon.DataModelByXml(resultmodel.Value, "").OuterXml));
                        deduceInputModelList.Add(result);
                    }
                }
                else
                {
                    if (causeIds != null && causeIds.Any())
                    {
                        foreach (var item in causeIds)
                        {
                            DeduceInputModel result = SetDeduceInput("MSCaseDeduction", dataContext.DataLayerAns.CaseId, dataContext.DataLayerAns.CaseType, item,
                                dataContext.DataLayerAns.Shujuneirong.Anjianid, HttpHelp.EnDataBase64(dataContext.DataLayerOpt.OptimizationXml.OuterXml), "");
                            deduceInputModelList.Add(result);
                        }
                    }
                    else
                    {
                        DeduceInputModel result = SetDeduceInput("MSCaseDeduction", dataContext.DataLayerAns.CaseId, dataContext.DataLayerAns.CaseType, "",
                                dataContext.DataLayerAns.Shujuneirong.Anjianid, HttpHelp.EnDataBase64(dataContext.DataLayerOpt.OptimizationXml.OuterXml), "");
                        deduceInputModelList.Add(result);
                    }
                }
            }
            else if (type == "aom")
            {
                if (causeIds != null && causeIds.Any())
                {
                    foreach (var item in causeIds)
                    {
                        DeduceInputModel result = SetDeduceInput("MSCaseDeduction", dataContext.DataLayerAns.CaseId, dataContext.DataLayerAns.CaseType, item,
                            dataContext.DataLayerAns.Shujuneirong.Anjianid, HttpHelp.EnDataBase64(dataContext.DataLayerOpt.OptimizationXml.OuterXml), "");
                        deduceInputModelList.Add(result);
                    }
                }
                else
                {
                    DeduceInputModel result = SetDeduceInput("MSCaseDeduction", dataContext.DataLayerAns.CaseId, dataContext.DataLayerAns.CaseType, "",
                            dataContext.DataLayerAns.Shujuneirong.Anjianid, HttpHelp.EnDataBase64(dataContext.DataLayerOpt.OptimizationXml.OuterXml), "");
                    deduceInputModelList.Add(result);
                }
            }
            return deduceInputModelList;
        }

        /// <summary>
        /// 组装推导请求参数
        /// </summary>
        /// <param name="code">推导规则代码</param>
        /// <param name="caseId">案件Id</param>
        /// <param name="caseType">案件类型编号</param>
        /// <param name="caseCauseId">案由Id</param>
        /// <param name="outRelatId">分析卷宗内容的案件Id</param>
        /// <param name="caseElement">案件要素</param>
        /// <param name="causeElement">案由要素</param>
        /// <returns></returns>
        public DeduceInputModel SetDeduceInput(string code, string caseId, string caseType, string caseCauseId, string outRelatId, string caseElement, string causeElement)
        {
            DeduceInputModel result = new DeduceInputModel();
            result.code = code;
            result.outParameter = new List<OutParameterItem>();
            result.outParameter.Add(SetoutParameterItem("CaseID", caseId, "String"));
            result.outParameter.Add(SetoutParameterItem("CaseType", caseType, "String"));
            result.outParameter.Add(SetoutParameterItem("CaseCauseID", caseCauseId, "String"));
            result.outParameter.Add(SetoutParameterItem("OutRelatID", outRelatId, "String"));
            result.outParameter.Add(SetoutParameterItem("CaseElementXml", caseElement, "base64"));
            result.outParameter.Add(SetoutParameterItem("CauseElementXml", causeElement, "base64"));
            if (!string.IsNullOrWhiteSpace(dataContext.DataLayerAns.District))
                result.outParameter.Add(SetoutParameterItem("District", dataContext.DataLayerAns.District, "String"));
            if (dataContext.DataLayerAns.StageProcessAnalysisDataModel != null && dataContext.DataLayerOpt.SourdatModleList != null && dataContext.DataLayerOpt.SourdatModleList.Count > 0)
            {
                string stage = "";
                if (dataContext.DataLayerAns.StageProcessAnalysisModel != null && dataContext.DataLayerAns.StageProcessAnalysisModel.dataModel != null)
                {
                    DataModel dataModel = XmlUtility.ConditionFirstOrDefaultDataModel(dataContext.DataLayerOpt.SourdatModleList, "", dataContext.DataLayerAns.StageProcessAnalysisModel.path);
                    stage = dataModel.AttributesList.FirstOrDefault(a => a.Name == "阶段").sourceList[0].SaveValue;
                }

                result.outParameter.Add(SetoutParameterItem("TrialProcedure", stage, "String"));
            }
            return result;
        }

        /// <summary>
        /// 推导参数列表项
        /// </summary>
        /// <param name="key">参数名称</param>
        /// <param name="value">参数值</param>
        /// <param name="type">参数类型</param>
        /// <returns></returns>
        public OutParameterItem SetoutParameterItem(string key, string value, string type = "")
        {
            OutParameterItem outParameterItem = new OutParameterItem();
            outParameterItem.code = key;
            outParameterItem.Value = value;
            outParameterItem.Type = type;
            return outParameterItem;
        }

        /// <summary>
        /// 调用推导服务获取推导结果
        /// </summary>
        /// <param name="deduceInput">推导参数</param>
        /// <returns></returns>
        public Dictionary<string, List<string>> GetDeduceResult(DeduceInputModel deduceInput, string code, string project, string deduceType)
        {
            var deduceTraceId = Snowflake.Instance().GetId().ToString();
            dataContext.InteractiveShow.LogShow("对接推导服务：开始发送post请求调用推导服务接口,MessageId:" + deduceTraceId);
            Dictionary<string, List<string>> result = new Dictionary<string, List<string>>();
            List<string> cacseDeduceResults = new List<string>();
            RequestDataModel deduceResponse = new RequestDataModel();
            try
            {
                string re = string.Empty;
                DeduceInputModel sendParameter = new DeduceInputModel();
                sendParameter.code = code;
                sendParameter.project = project;
                sendParameter.outParameter = new List<OutParameterItem>();
                sendParameter.outParameter = deduceInput.outParameter;
                string url = ConfigRetrieval.GetConfigRetrieval.GetAppSettingString("RuleParseServer") + "/common/v1/rulededuce2/parse_cause_type";
                string postData = JsonConvert.SerializeObject(sendParameter);
                Dictionary<string, string> deduceHeaders = new Dictionary<string, string>();
                deduceHeaders.Add("traceId", deduceTraceId);
                try
                {
                    Stopwatch swtext = new Stopwatch();
                    swtext.Start();
                    re = HttpHelp.HttpPostJson(url, postData, deduceHeaders);
                    swtext.Stop();
                    dataContext.InteractiveShow.LogShow("推导服务调用时间：" + swtext.Elapsed.TotalMilliseconds.ToString("0"));
                    deduceResponse.RequestKey = deduceType + "_" + Snowflake.Instance().GetId().ToString();
                    deduceResponse.RequestUrl = url;
                    deduceResponse.RequestParam = postData;
                    deduceResponse.RequestResult = re;
                    JArray ja = (JArray)JsonConvert.DeserializeObject(re);
                    if (ja.Count > 0)
                    {
                        cacseDeduceResults.Add(re);
                        result.Add("case", cacseDeduceResults);
                    }
                    dataContext.InteractiveShow.LogShow("对接推导服务：接口返回" + re);

                }
                catch (System.Exception inex)
                {
                    dataContext.InteractiveShow.LogShow("******************* ********************", LogMessageType.Error);
                }
            }
            catch (System.Exception ex)
            {
                dataContext.InteractiveShow.LogShow("********************对接推导服务GetDeduceResult发生错误" + ex.Message, LogMessageType.Error);
                dataContext.InteractiveShow.LogShow(ex.StackTrace, LogMessageType.Error);
            }
            if (DeduceRequestModels.Any(x => x.RequestKey == deduceType))
            {
                var delData = DeduceRequestModels.FirstOrDefault(x => x.RequestKey == deduceType);
                DeduceRequestModels.Remove(delData);
            }
            DeduceRequestModels.Add(deduceResponse);
            return result;
        }

        /// <summary>
        /// 更新xml
        /// </summary>
        /// <param name="result">推导服务返回的结果</param>
        /// <param name="flag">
        /// 0：分析之后的推导
        /// 1：优选之后的推导
        /// 2：分人员要素分析后推导
        /// 3：分人员要素优选后，合并前推导
        /// </param>
        /// <returns></returns>
        public string UpdateXml(Dictionary<string, List<string>> result, int flag, string causeID, string linShi = "")
        {
            dataContext.InteractiveShow.LogShow("根据推导信息开始更新XML服务");
            string res = string.Empty;
            List<DataModel> listSource = new List<DataModel>();
            try
            {
                if (result.Count < 1)
                {
                    return "";
                }
                XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = dataContext };
                if (!string.IsNullOrEmpty(linShi))
                {
                    XmlDocument nodeDocument = new XmlDocument();
                    nodeDocument.LoadXml(linShi);
                    List<DataModel> listNew = xmlUtilCommon.GetXMLByDataModelBackFill(nodeDocument).dataModelList;
                   
                    if (flag == 0)
                    {
                        listSource = dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList;
                        dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList = listNew;
                    }
                    else if (flag == 1)
                    {
                        listSource = dataContext.DataLayerOpt.SourdatModleList;
                        dataContext.DataLayerOpt.SourdatModleList = listNew;
                    }
                    else if (flag == 2)
                    {
                        listSource = dataContext.DataLayerAns.ElementAnalsisDataModelResults[causeID];
                        dataContext.DataLayerAns.ElementAnalsisDataModelResults[causeID] = listNew;
                    }
                    else if (flag == 3)
                    {
                        listSource = dataContext.DataLayerOpt.SourdatModleList;
                        dataContext.DataLayerOpt.SourdatModleList = listNew;
                    }
                }

                XmlDocument sourceXml = new XmlDocument(), targetXml = new XmlDocument();
                foreach (var kv in result)
                {
                    foreach (var value in kv.Value)
                    {
                        #region 将Jarray转到类中
                        DeduceResultList resultList = new DeduceResultList();
                        resultList.DeduceOutResult = new List<DeduceResultModel>();
                        JArray ja = (JArray)JsonConvert.DeserializeObject(value);
                        foreach (var jToken in ja)
                        {
                            JObject jo = (JObject)jToken;
                            DeduceResultModel joModel = JsonConvert.DeserializeObject<DeduceResultModel>(jo.ToString());
                            resultList.DeduceOutResult.Add(joModel);

                        }
                        if (resultList.DeduceOutResult != null && resultList.DeduceOutResult.Count > 0)
                        {
                            DeduceResultModel deduceModel = resultList.DeduceOutResult.FirstOrDefault(a => !string.IsNullOrEmpty(a.DeleteData));
                            if (deduceModel != null)
                            {
                                List<DataModel> ruleModellist = new List<DataModel>();
                                if (flag == 0)
                                {
                                    ruleModellist = dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList;
                                }
                                else if (flag == 1)
                                {
                                    ruleModellist = dataContext.DataLayerOpt.SourdatModleList;
                                }
                                else if (flag == 2)
                                {
                                    ruleModellist = dataContext.DataLayerAns.ElementAnalsisDataModelResults[causeID];
                                }
                                else if (flag == 3)
                                {
                                    ruleModellist = dataContext.DataLayerOpt.SourdatModleList;
                                }
                                string xmlpath = deduceModel.DeleteData;
                                DataModel xmlModel = XmlUtility.ConditionFirstOrDefaultDataModel(ruleModellist, "", xmlpath);
                                List<DataModel> debugModelList = xmlUtilCommon.SubordinateDataModelList(ruleModellist, xmlModel);
                                foreach (var item in debugModelList)
                                {
                                    ruleModellist.Remove(item);
                                }
                            }

                        }

                        #endregion
                        // 获取每条规则执行后的结果集合List<一条规则执行后的结果>
                        List<List<ElementOutVo>> deduceResult = resultList.DeduceOutResult.Select(a => a.Result).ToList();
                        // 遍历规则结果
                        foreach (List<ElementOutVo> item in deduceResult)
                        {

                            string type = string.Empty;
                            if (item.Where(a => a.Name == "状态").ToList().Count > 0)
                            {
                                type = item.Where(a => a.Name == "状态").ToList()[0].OperateResult;
                            }
                            string stage = "";
                            if (item.Where(a => a.Name == "阶段").ToList().Count > 0)
                            {
                                stage = item.Where(a => a.Name == "阶段").ToList()[0].OperateResult;
                            }
                            foreach (ElementOutVo outVo in item)
                            {
                                if (outVo.Name != "状态" && outVo.Name != "数据处理类型" && outVo.Name != "阶段" && outVo.checkCode != "0")
                                {
                                    outVo.Path = outVo.Path.TrimStart('/');
                                    string attname = outVo.Path?.Split('/')[outVo.Path.Split('/').Length - 1];
                                    string path = outVo.Path?.Replace(@"/" + attname, "");
                                    path = "";
                                    string strpath = "";
                                    for (int i = 0; i < outVo.Path?.Split('/').Length - 1; i++)
                                    {
                                        if (path == "")
                                        {
                                            path = outVo.Path?.Split('/')[i];
                                        }
                                        else
                                        {
                                            path = path + "/" + outVo.Path?.Split('/')[i];
                                        }
                                    }
                                    if (dataContext.DataLayerAns.CaseCausesList != null && dataContext.DataLayerAns.CaseCausesList.Count > 0 && flag != 2)
                                    {
                                        if (path.IndexOf("案由要素") > -1)
                                        {
                                            if (flag != 3)
                                            {
                                                if (dataContext.DataLayerAns.CaseType.ToLower() == "jb1" || dataContext.DataLayerAns.CaseType.ToLower() == "ja1" || dataContext.DataLayerAns.CaseType.ToLower() == "jg2")
                                                {
                                                    path = @"/案件信息要素中心/案件办理阶段/详情[@阶段='" + stage + "']/案由信息/详情/合并后要素/" + path;
                                                }
                                                else if (dataContext.DataLayerAns.CaseType.ToLower() == "xzzf")
                                                {
                                                    path = @"/案件信息要素中心/案件审理阶段/详情[@阶段='" + stage + "']/违法行为涉及领域/合并后要素/" + path;
                                                }
                                                else if (dataContext.DataLayerAns.CaseType.ToLower() == "ldzc")
                                                {
                                                    path = @"/案件信息要素中心/仲裁/审理/案件审理阶段/详情[@阶段='" + stage + "']/案由信息/详情/合并后要素/" + path;
                                                }
                                                else
                                                {
                                                    path = @"/案件信息要素中心/审判/一审/案件审理阶段/详情[@阶段='" + stage + "']/案由信息/详情/合并后要素/" + path;
                                                }
                                            }
                                            else
                                            {
                                                strpath = path;
                                                if (dataContext.DataLayerAns.CaseType.ToLower() == "jb1" || dataContext.DataLayerAns.CaseType.ToLower() == "ja1" || dataContext.DataLayerAns.CaseType.ToLower() == "jg2")
                                                {
                                                    path = @"/案件信息要素中心/案件办理阶段/详情/案由信息/详情/分人员要素/" + path;
                                                }
                                                else if (dataContext.DataLayerAns.CaseType.ToLower() == "xzzf")
                                                {
                                                    path = @"/案件信息要素中心/案件审理阶段/详情/违法行为涉及领域/分人员要素/" + path;
                                                }
                                                else if (dataContext.DataLayerAns.CaseType.ToLower() == "ldzc")
                                                {
                                                    path = @"/案件信息要素中心/仲裁/审理/案件审理阶段/详情[@阶段='" + stage + "']/案由信息/详情/分人员要素/" + path;
                                                }
                                                else
                                                if (dataContext.DataLayerAns.CaseType.ToLower() == "a1")
                                                {
                                                    path = @"/案件信息要素中心/审判/一审/案件审理阶段/详情[@阶段='" + stage + "']/案由信息/详情/分人员要素/" + path;
                                                }
                                                else
                                                {
                                                    path = @"/案件信息要素中心/审判/一审/案件审理阶段/详情[@阶段='" + stage + "']/案由信息/详情/分人员要素/" + path;
                                                }
                                            }
                                        }
                                    }

                                    List<DataModel> list = new List<DataModel>();
                                    List<DataModel> modelList = new List<DataModel>();
                                    Dictionary<string, List<DataModel>> dicValue = new Dictionary<string, List<DataModel>>();

                                    if (flag == 0)
                                    {
                                        list = dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList;
                                        dicValue.Add("0", list);
                                    }
                                    else if (flag == 1)
                                    {
                                        list = dataContext.DataLayerOpt.SourdatModleList;
                                    }
                                    else if (flag == 2)
                                    {
                                        list = dataContext.DataLayerAns.ElementAnalsisDataModelResults[causeID];
                                    }
                                    else if (flag == 3)
                                    {
                                        list = dataContext.DataLayerOpt.SourdatModleList;
                                        modelList = dataContext.DataLayerOpt.ElementOptimizationResults[causeID];
                                        sourceXml = xmlUtilCommon.DataModelByXml(modelList, "");
                                    }
                                    
                                    if (list.Count > 0)
                                    {
                                        string id = xmlUtilCommon.CaseNodeUpdate(list, path);
                                        List<DataModel> dataModelList = XmlUtility.ConditionDataModelList(list, "", path);

                                        if (dataModelList.Count == 1 ||
                                            dataModelList.FirstOrDefault(a => a.AttributesList.FirstOrDefault(b => b.sourceList.FirstOrDefault(c => c.SaveValue == outVo.OperateResult) == null && b.Name == attname.Replace("@", "")) == null) == null)
                                        {
                                            DataModel dataModel = list.FirstOrDefault(a => a.ID == id);
                                            if (dataModel.AttributesList == null || dataModel.AttributesList.FirstOrDefault(a => a.Name == attname.Replace("@", "")) == null)
                                            {

                                                Source source = new Source();
                                                source.SourceCode = dataContext.DataLayerAns.SourceCode;
                                                source.SaveValue = outVo.OperateResult;
                                                source.IsCheck = "1";
                                                AttributeInfo attribute = new AttributeInfo();
                                                if (dataModel.AttributesList == null)
                                                {
                                                    dataModel.AttributesList = new List<AttributeInfo>();
                                                }

                                                attribute.Name = attname.Replace("@", "");
                                                attribute.sourceList = new List<Source>();
                                                attribute.sourceList.Add(source);
                                                dataModel.AttributesList.Add(attribute);

                                            }
                                            else
                                            {
                                                var dataAtt = dataModel.AttributesList.FirstOrDefault(a => a.Name == attname.Replace("@", ""));
                                                if (dataAtt.sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue != outVo.OperateResult)
                                                {
                                                    dataAtt.sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue = outVo.OperateResult;

                                                }
                                            }


                                        }

                                    }
                                    if (modelList.Count > 0)
                                    {

                                        if (modelList.FirstOrDefault(a => a.ParentId == "") == null)
                                        {
                                            if (dataContext.DataLayerAns.CaseCausesList.Count > 0)
                                            {
                                                DataModel dataModelr = new DataModel();
                                                dataModelr.ID = dataContext.DataLayerAns.CaseCausesList[0].CC_ID;
                                                dataModelr.ParentId = "";
                                                dataModelr.XmlPath = "案由要素/";
                                                modelList.Add(dataModelr);
                                            }
                                        }
                                        if (!string.IsNullOrWhiteSpace(strpath))
                                        {
                                     
                                            string id = xmlUtilCommon.CaseNodeUpdate(modelList, strpath);
                                            List<DataModel> dataModelList = XmlUtility.ConditionDataModelList(modelList, "", strpath);
                                            if (dataModelList.Count == 1 ||
                                                dataModelList.FirstOrDefault(a => a.AttributesList.FirstOrDefault(b => b.sourceList.FirstOrDefault(c => c.SaveValue == outVo.OperateResult) == null && b.Name == attname.Replace("@", "")) == null) == null)
                                            {
                                                DataModel dataModel = modelList.FirstOrDefault(a => a.ID == id);
                                                if (dataModel.AttributesList == null || dataModel.AttributesList.FirstOrDefault(a => a.Name == attname.Replace("@", "")) == null)
                                                {

                                                    Source source = new Source();
                                                    source.SourceCode = dataContext.DataLayerAns.SourceCode;
                                                    source.SaveValue = outVo.OperateResult;
                                                    source.IsCheck = "1";
                                                    AttributeInfo attribute = new AttributeInfo();
                                                    if (dataModel.AttributesList == null)
                                                    {
                                                        dataModel.AttributesList = new List<AttributeInfo>();
                                                    }

                                                    attribute.Name = attname.Replace("@", "");
                                                    attribute.sourceList = new List<Source>();
                                                    attribute.sourceList.Add(source);
                                                    dataModel.AttributesList.Add(attribute);

                                                }
                                                else
                                                {
                                                    var dataAtt = dataModel.AttributesList.FirstOrDefault(a => a.Name == attname.Replace("@", ""));
                                                    if (dataAtt.sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue != outVo.OperateResult)
                                                    {
                                                        dataAtt.sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue = outVo.OperateResult;

                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                

                if (flag == 0)
                {
                    sourceXml = dataContext.DataLayerAns.AnalysisResultsXml;
                    targetXml = xmlUtilCommon.DataModelByXml(dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList, "");
                    if (!string.IsNullOrWhiteSpace(linShi))
                    {
                        res = targetXml.OuterXml;
                    }
                    else
                    {
                        dataContext.DataLayerAns.AnalysisResultsXml = targetXml;
                    }
                    if (listSource.Count > 0)
                    {
                        dataContext.DataLayerAns.AnalysisResultsDataModel.dataModelList = listSource;
                    }
                }
                else if (flag == 1)
                {
                    sourceXml = dataContext.DataLayerOpt.OptimizationXml;
                    targetXml = xmlUtilCommon.DataModelByXml(dataContext.DataLayerOpt.SourdatModleList, "");
                    if (!string.IsNullOrWhiteSpace(linShi))
                    {
                        res = targetXml.OuterXml;
                    }
                    else
                    {
                        dataContext.DataLayerOpt.OptimizationXml = targetXml;
                    }
                    if (listSource.Count > 0)
                    {
                        dataContext.DataLayerOpt.SourdatModleList = listSource;
                    }
                }
                else if (flag == 2)
                {
                    sourceXml = dataContext.DataLayerAns.ElementAnalysisResults[causeID];
                    targetXml = xmlUtilCommon.DataModelByXml(dataContext.DataLayerAns.ElementAnalsisDataModelResults[causeID], "");
                    if (!string.IsNullOrWhiteSpace(linShi))
                    {
                        res = targetXml.OuterXml;
                    }
                    else
                    {
                        dataContext.DataLayerAns.ElementAnalysisResults[causeID] = targetXml;
                    }
                    if (listSource.Count > 0)
                    {
                        dataContext.DataLayerAns.ElementAnalsisDataModelResults[causeID] = listSource;
                    }
                }
                else if (flag == 3)
                {
                    //XmlDocument document = new XmlDocument();
                    //if (!string.IsNullOrEmpty(dataContext.DataLayerOpt.OptimizeCauseEntityXml))
                    //{
                    //    document.LoadXml(dataContext.DataLayerOpt.OptimizeCauseEntityXml);
                    //    sourceXml = document;
                    //}
                    targetXml = xmlUtilCommon.DataModelByXml(dataContext.DataLayerOpt.ElementOptimizationResults[causeID], "");
                    if (!string.IsNullOrWhiteSpace(linShi))
                    {
                        res = targetXml.OuterXml;
                    }
                    else
                    {
                        dataContext.DataLayerOpt.OptimizeCauseEntityXml = targetXml.OuterXml;
                    }
                    if (listSource.Count > 0)
                    {
                        dataContext.DataLayerOpt.SourdatModleList = listSource;
                    }
                }
                if (!string.IsNullOrWhiteSpace(linShi))
                {
                    res = targetXml.OuterXml;
                }
                else
                {
                    SetXml(result, sourceXml, targetXml);
                }
            }
            catch (System.Exception ex)
            {
                List<DataModel> dataModels = dataContext.DataLayerAns.ElementAnalsisDataModelResults[causeID];
                dataContext.InteractiveShow.LogShow("******************对接推导服务UpdateXml发生错误" + ex.ToString(), LogMessageType.Error);
            }
            return res;
        }




        /// <summary>
        /// 设置推导前的xml与推导后的xml 
        /// </summary>
        /// <param name="result">推导结果</param>
        /// <param name="sourceXml">推导前xml</param>
        /// <param name="targetXml">推导后xml</param>
        private void SetXml(Dictionary<string, List<string>> result, XmlDocument sourceXml, XmlDocument targetXml)
        {
            DeduceRequestModels.ForEach(x =>
            {
                foreach (var kv in result)
                {
                    foreach (var value in kv.Value)
                    {
                        if (x.RequestResult == value)
                        {
                            x.RequestXml = sourceXml?.OuterXml;
                            x.ResposeXml = targetXml?.OuterXml;
                            break;
                        }
                    }
                }
            });
        }

        /// <summary>
        /// 删除数据对应节点
        /// </summary>
        /// <param name="xmlpath"></param>
        /// <param name="flag"></param>
        public void DelectNode(string xmlpath, int flag)
        {

        }
    }
}
